package com.ftg.learn.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ftg.learn.system.entity.Role;
import com.ftg.learn.system.service.IRoleService;
import com.ftg.learn.util.JsonWeb;
import com.ftg.learn.util.JsonWebUtil;
import com.ftg.learn.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 角色管理
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/4/27 下午1:42
 */
@Api(tags = "角色管理")
@RequestMapping("/api/system/role")
@Slf4j
@RestController
public class RoleController {

    @Resource
    IRoleService iRoleService;

    @Resource
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("/page")
    @ApiOperation("角色列表功能")
    public JsonWeb<IPage<Role>> page(
            @ApiParam(value = "当前页数") @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页显示条数") @RequestParam(value = "limit", defaultValue = "10") Integer limit,
            @ApiParam(value = "角色名称") @RequestParam(value = "roleName", required = false) String roleName,
            @ApiParam(value = "角色key") @RequestParam(value = "rolekey", required = false) String rolekey
    ) {

        //sprinboot 内置一个request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes req = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = req.getRequest();

        //只能访问地址
        String url = request.getRequestURI();
        String query = request.getQueryString();
        log.info("用来测试一下url{} query {}",url,query);

        String key = url + query;

        if (!stringRedisTemplate.hasKey(key)) {
            IPage<Role> ipage = new Page<>(pageNo, limit);
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(StringUtils.isNotBlank(roleName), "role_name", roleName);
            queryWrapper.like(StringUtils.isNotBlank(rolekey), "role_key", rolekey);
            IPage<Role> list = iRoleService.page(ipage, queryWrapper);

            // 存取到redis
            String redisVal = JSON.toJSONString(list);
            long timeLong = (long) (Math.random() * 2000) + 1000;
            stringRedisTemplate.opsForValue().set(key, redisVal, timeLong, TimeUnit.SECONDS);
        }
        //我们要先把redis里面的字符串取出来
        String redisVal = stringRedisTemplate.opsForValue().get(key);
        //转换成为jsonobject对象
        JSONObject json = JSON.parseObject(redisVal);
        //json.toJavaObject(IPage.class) 再把这个jsonobject转换成为类
        return JsonWebUtil.success(json.toJavaObject(IPage.class));
    }

    @PostMapping("/save")
    @ApiOperation("角色添加功能")
    public JsonWeb<Boolean> save(@RequestBody Role role
    ) {
        boolean issucc = iRoleService.save(role);
        if(issucc){
            stringRedisTemplate.delete(stringRedisTemplate.keys("/api/system/role*"));
        }
        return JsonWebUtil.success(issucc);
    }


    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("角色删除功能")
    public JsonWeb<Boolean> deleteById(@PathVariable(value = "id") Serializable id) {
        return JsonWebUtil.success(iRoleService.removeById(id));
    }


    @DeleteMapping("/deleteByIds/{id}")
    @ApiOperation("批量角色删除功能")
    public JsonWeb<Boolean> deleteByIds(@PathVariable(value = "id") List<Serializable> id) {
        return JsonWebUtil.success(iRoleService.removeByIds(id));
    }

    @PutMapping("/roleModify")
    @ApiOperation("角色修改操作")
    public JsonWeb<Boolean> roleModify(@RequestBody Role role) {
        return JsonWebUtil.success(iRoleService.updateById(role));
    }

    @GetMapping("/showPrivilege")
    @ApiOperation("角色授权操作")
    public JsonWeb<List<Integer>> showPrivilege(
            @RequestHeader("token") String token
    ) {
        //鉴权 auth0 auth2 spring security [4]
        Claims body = JwtUtil.verifyJwtToken(token);
        if (Objects.isNull(body)) {
            return JsonWebUtil.tokenInvalidToken();
        }

        //从token里获得当前用户的编号,
        Integer id = Integer.valueOf(body.get("id").toString());

        // 再通过用户编号取到用户的所有角色编号
        List<Integer> roleIds = iRoleService.allRoleWithUserId(id);

        if (roleIds.size() == 0) {
            return JsonWebUtil.success(null);
        }

        return JsonWebUtil.success(iRoleService.privilegeByRoleId(roleIds));
    }

    @ApiOperation("角色管理之授权功能")
    @PostMapping("/saveRoleMenu")
    public JsonWeb<?> saveRoleMenu(@RequestParam("mids") List<Integer> mids, Integer roleId) {
        return JsonWebUtil.success(null);
    }

}
